package xp.ass.imitate.tools;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import xp.ass.imitate.spring.tools.ApplicationContextHolder;

/**
 * @author chent3
 * @date 2024/7/17
 */
public class JsonUtils {


    private static ObjectMapper objectMapper;

    private static ObjectMapper getMapper() {
        try {
            return ApplicationContextHolder.getApplicationContext().getBean(ObjectMapper.class);
        } catch (Exception ignore) {
        }
        return objectMapper == null ? objectMapper = initObjectMapper() : objectMapper;
    }

    private static ObjectMapper initObjectMapper() {
        return new ObjectMapper();
    }


    public static String toJson(Object object) {
        try {
            return getMapper().writeValueAsString(object);
        }catch (JsonProcessingException ex){
            throw new RuntimeException(ex);
        }
    }

    public static String toJsonWithPretty(Object object) {
        try {
             return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
        }catch (JsonProcessingException ex){
            throw new RuntimeException(ex);
        }
    }



}
